//
//  FZleftDrawerViewController.swift
//  Pods
//
//  Created by IMM on 2025/4/18.
//

import UIKit

open class FZMainDrawerViewController: UIViewController {
    
    /// 是否开启
    open var isOpen:Bool{
        return self.isLeftDrawerOpen || self.isLeftDrawerOpen
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    /// 主视图
    private var mainDrawerViewController:UIViewController!
    /// 左视图
    private var leftDrawerViewController: UIViewController?
    /// 右视图
    private var rightDrawerViewController: UIViewController?
    /// 左视图是否开启
    private var isLeftDrawerOpen = false
    /// 右视图是否开启
    private var isRightDrawerOpen = false
    /// 记录左视图偏移的距离
    private var leftStartX: CGFloat = 0
    /// 记录右视图偏移的距离
    private var rightStartX: CGFloat = 0
    /// 左视图的宽度
    private var leftDrawerXWidth:CGFloat = 0
    /// 右视图的宽度
    private var rightDrawerXWidth:CGFloat = 0
    /// 遮罩视图
    public var overlayView: UIView! // 添加遮罩视图属性
    
    /// 配置信息
    private var config:FZDrawerConfig
    
    // 边距margin
    private var leftDrawerX:CGFloat{
        return mainContainerView.frame.width - leftDrawerXWidth
    }
    
    @objc private func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {
        let translation = recognizer.translation(in: view)
        let velocity = recognizer.velocity(in: view)

        switch recognizer.state {
        case .began:
            if let leftDrawerViewController = leftDrawerViewController {
                leftStartX = leftDrawerViewController.view.frame.origin.x
            }
            if let rightDrawerViewController = rightDrawerViewController {
                rightStartX = rightDrawerViewController.view.frame.origin.x
            }
        case .changed:
            if !isLeftDrawerOpen && !isRightDrawerOpen {
                if translation.x < 0 {
                    isLeftDrawerOpen = false
                    isRightDrawerOpen = true
                } else if translation.x > 0 {
                    isLeftDrawerOpen = true
                    isRightDrawerOpen = false
                }
            } else if isLeftDrawerOpen {
                if let leftDrawerViewController = leftDrawerViewController {
                    let newX = leftStartX + translation.x
                    if newX <= 0 {
                        leftDrawerViewController.view.frame.origin.x = newX
                        mainContainerView.frame.origin.x = newX + mainContainerView.frame.width - leftDrawerX
                    }
                }
            } else if isRightDrawerOpen {
                if let rightDrawerViewController = rightDrawerViewController {
                    let newX = rightStartX + translation.x
                    if newX >= 0 {
                        let rightX = newX
                        let maxRightX = view.frame.width - rightDrawerViewController.view.frame.width
                        if rightX > maxRightX{
                            rightDrawerViewController.view.frame.origin.x = rightX
                            mainContainerView.frame.origin.x = -(view.bounds.width - rightX)
                        }
                    }
                }
            }
        case .ended, .cancelled:
            if isLeftDrawerOpen {
                if let leftDrawerViewController = leftDrawerViewController {
                    if velocity.x < -500 {
                        closeDrawer()
                    } else if leftDrawerViewController.view.frame.origin.x > -leftDrawerViewController.view.frame.width / 1.2 {
                        openDrawer()
                    } else {
                        closeDrawer()
                    }
                }
                
            } else if isRightDrawerOpen {
                if let rightDrawerViewController = rightDrawerViewController {
                    if velocity.x > 500 {
                        closeRight()
                    } else if rightDrawerViewController.view.frame.origin.x > view.bounds.width / 1.2 {
                        closeRight()
                    } else {
                        openRight()
                    }
                }
            }
        default:
            break
        }
    }

    @objc private func handleTapGesture(_ recognizer: UITapGestureRecognizer) {
        if isLeftDrawerOpen {
            closeDrawer()
        }
        
        if isRightDrawerOpen{
            closeRight()
        }
    }

    open func openDrawer() {
        if let leftDrawerViewController = leftDrawerViewController {
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
                leftDrawerViewController.view.frame.origin.x = 0
                self.mainContainerView.frame.origin.x = self.leftDrawerXWidth
                self.overlayView.alpha = 0.4 // 显示遮罩
            }) { _ in
                self.isLeftDrawerOpen = true
            }
        }
    }

    open func closeDrawer() {
        if let leftDrawerViewController = leftDrawerViewController {
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
                leftDrawerViewController.view.frame.origin.x = -leftDrawerViewController.view.frame.width
                self.mainContainerView.frame.origin.x = 0
                self.overlayView.alpha = 0 // 隐藏遮罩
            }) { _ in
                self.isLeftDrawerOpen = false
            }
        }
    }
    
    open func openRight() {
        if let rightDrawerViewController = rightDrawerViewController {
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
                rightDrawerViewController.view.frame.origin.x = self.view.bounds.width - self.rightDrawerXWidth
                self.mainContainerView.frame.origin.x = -rightDrawerViewController.view.frame.width
                self.overlayView.alpha = 0.4
            }) { _ in
                self.isRightDrawerOpen = true
            }
        }

    }
    
    open func closeRight() {
        if let rightDrawerViewController = rightDrawerViewController {
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
                rightDrawerViewController.view.frame.origin.x = self.view.bounds.width
                self.mainContainerView.frame.origin.x = 0
                self.overlayView.alpha = 0
            }) { _ in
                self.isRightDrawerOpen = false
            }
        }
    }
    
    private lazy var mainContainerView:UIView = {
        let view = config.mainDrawerVc?.view
        return view ?? UIView()
    }()

    public init(config: FZDrawerConfig) {
        self.config = config
        mainDrawerViewController = config.mainDrawerVc
        leftDrawerViewController = config.leftDrawerVc
        rightDrawerViewController = config.rightDrawerVc
        leftDrawerXWidth = config.leftDrawerWidth
        rightDrawerXWidth = config.rightDrawerWidth
        super.init(nibName: nil, bundle: nil)
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    open override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white

        // 赋值单例
        FZDrawerManager.shared.drawer = self
        
        // 初始化主视图容器
        mainContainerView.frame = view.bounds
        view.addSubview(mainContainerView)
        self.addChild(mainDrawerViewController)
        mainDrawerViewController.didMove(toParent: self)

        // 初始化遮罩视图
        overlayView = UIView(frame: view.bounds)
        overlayView.backgroundColor = UIColor.gray
        overlayView.alpha = 0
        mainContainerView.addSubview(overlayView)
        
        // 初始化抽屉视图
        let drawerHeight = view.bounds.height
        if let leftDrawerViewController = leftDrawerViewController {
            leftDrawerViewController.view.frame = CGRect(x: -leftDrawerXWidth, y: 0, width: leftDrawerXWidth, height: drawerHeight)
            self.addChild(leftDrawerViewController)
            view.addSubview(leftDrawerViewController.view)
            leftDrawerViewController.didMove(toParent: self)
        }

        // 初始化右侧视图
        if let rightDrawerViewController = rightDrawerViewController {
            rightDrawerViewController.view.frame = CGRect(x: view.bounds.width, y: 0, width: rightDrawerXWidth, height: drawerHeight)
            self.addChild(rightDrawerViewController)
            view.addSubview(rightDrawerViewController.view)
            rightDrawerViewController.didMove(toParent: self)
        }

        if config.isEnableGestures{
            // 添加手势识别器
            let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
            view.addGestureRecognizer(panGesture)
        }
        
        // 添加点击手势识别器
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
        tapGesture.cancelsTouchesInView = false
        overlayView.addGestureRecognizer(tapGesture)
    }
}

